<div class="content">
	<textarea id="pre">
		//router.js

		import Vue from 'vue';
		import Router from 'vue-router';
		import authority from "@/components/js/authority";
		import Cache from "../components/js/Cache";
		Vue.use(Router);

		import store from './store';

		/**
		 * 解决VUE路由两次访问相同路由地址报错
		 */
		const originalPush = Router.prototype.push;
		Router.prototype.push = function push(location) {
		    return originalPush.call(this, location).catch(err => err)
		};

		export const constantRouterMap = [
			{
		        path: 'layout',
		        component: resolve => require(['../components/common/Layout.vue'], resolve),
		        meta: {
		            title: '后台管理系统'
		        },
		        children: [
		            {
		                name: "setup",
		                meta: {
		                    title: '系统设置'
		                },
		                path: '/system/setup/index',
		                component: resolve => require(['../page/system/setup/index.vue'], resolve)
		            },
		        ]
		    }
		]
		
		const router = new Router({
		    scrollBehavior: () => ({y: 0}),
		    routes: constantRouterMap
		});

		/**
		 * 使用钩子函数对路由进行权限跳转
		 */
		router.beforeEach((to, from, next) => {
		    if (to.meta.auth instanceof Array && to.meta.auth.length > 0) {
		        if (!authority.check(to.meta.auth)) {
		            return next('/403')
		        }
		    }
		    if (to.meta.title) {
		        document.title = to.meta.title;
		    } else {
		        document.title = location.host;
		    }
		    if (store.state.authority.authorize) {//已经登录
		        if (to.name === 'login') return next('/login');
		        next();
		    } else if (to.name === 'login') {//已经在登录页面
		        next();
		    } else {
		        try {
		            let userData = Cache.get('authority-state');
		            if (!userData) return next('/login');
		            userData = JSON.parse(userData);
		            if (userData.id && userData.token) {
		                return next();
		            } else {
		                return next('/login')
		            }
		        } catch (e) {
		            return next();
		        }
		    }
		});



		//components/js/authority

		import store from "@/vue/store";

/**
 * 权限
 * @type {*[]}
 * @private
 */
const _permission = [];

/**
 * 精简权限名称
 */
function retrenchNodeName(node) {
    if (node.substr(0, 1) === '/') {
        return node.substr(1);
    }
    return node;
}

/**
 * 获取权限值
 */
function getPermission() {
    if (_permission.length === 0) {
        let permission = store.state.authority.permission;
        for (let node of permission) {
            _permission.push(retrenchNodeName(node));
        }
    }
    return _permission;
}


/**
 * 验证权限
 */
function check(authority) {
    if (authority === 1) {
        if (store.state.authority.role_id === -1 || store.state.authority.uid===1) {
            return true;
        } else {
            return false;
        }
    }
    let permission = getPermission();
    //role_id
    if (permission.indexOf('*') > -1) {
        return true;
    }
    if (typeof authority === "string") {
        authority = [authority];
    }
    let status = false;
    for (let sign of authority) {
        if (permission.indexOf(retrenchNodeName(sign)) >= 0) {
            return true;
        }
    }
    return status;
}

export default {
    check
}


		//store/module/permission.js

		import {constantRouterMap} from './../../router'

function hasPermission(roleRouers) {
    let routerItems = [];
    roleRouers.forEach((val) => {
        let item = getAsyncRouter(val);
        if (item) {
            routerItems.push(item);
        }
    });
    return routerItems;
}

function getAsyncRouter(roleRouter) {
    if (roleRouter['path'] && !roleRouter.children) {
        const arr = roleRouter['path'].split('/');
        const index = arr[arr.length - 1];
        return {
            path: roleRouter['path'],
            component: getViews(roleRouter['path']),
            meta: {title: roleRouter['name'], auth: roleRouter.node},
            index: index,
            name: roleRouter['name'],
        };
    }
    return false;

}

/**
 * 加载视图文件
 * @param path
 * @returns {function(...[*]=)}
 */
function getViews(path) {
    path = path.replace('page', '').split('/');
    let paths = [];
    path.forEach(item => {
        if (item) paths.push(item)
    });
    path = paths.join('/');
    return resolve => {
        require.ensure([], () => {
            resolve(require(`@/page/` + path + `.vue`))
        })
    }
}

//添加默认的路由
function addDefaultRouter(roleRouterItems) {
    let routerItems = [{
        path: '/',
        component: resolve => require(['@/components/common/Layout.vue'], resolve),
        meta: {title: 'layout'},
        children: [],
    }];
    let common = {
        path: '/dashboard',
        component: resolve => require(['@/page/dashboard/dashboard.vue'], resolve),
        meta: {title: '系统首页'},
        index: 'dashboard',
        name: '系统首页',
        icon: 'el-icon-s-home'
    };
    roleRouterItems.push(common);
    routerItems[0].children = roleRouterItems;
    let item404 = {
        path: '*',
        redirect: '../404'
    };
    routerItems.push(item404);
    return routerItems;
}


const permission = {
    namespace: true,
    state: {
        routers: constantRouterMap,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            let RouterItems = hasPermission(routers);
            //添加两个默认路由
            let roleRouterItems = addDefaultRouter(RouterItems);
            //动态添加的路由
            state.addRouters = roleRouterItems;
            //所有路由
            state.routers = constantRouterMap.concat(roleRouterItems);
        },

    },
    actions: {
        GenerateRoutes({commit}, data) {
            commit('SET_ROUTERS', data);
        },
    },

};
export default permission;


//store/module/authority.js

import cache from "@/components/js/Cache"
//用户状态s
export default {
    namespaced: true,

    state: {
        token: '',//后台TOKEN
        authorize: false,//登录状态
        avatar: "",//头像
        uid: 0,//ID号码
        last_login: '',//最后登录时间
        fullname: "",//用户名
        role_id: 0,
        phone: '',
        client_token: '',
        msg: 0,
        last_msg: [],
        last: 0,
        permission: [],
    },
    mutations: {
        //登录
        login(state, data) { //设置系统消息数
            cache.del('authority-state');
            state.token = data.token;
            state.authorize = true;
            state.role_id = parseInt(data.role_id);
            if (data.avatar) {
                state.avatar = data.avatar;
            }
            state.uid = parseInt(data.id);
            if (data.msg) {
                state.msg = parseInt(data.msg);
            }
            if (data.last) {
                state.last = parseInt(data.last);
            }
            if (data.last_msg) {
                state.last_msg = data.last_msg;
            }
            state.last_login = data.last_login;
            state.phone = data.phone;
            state.client_token = data.client_token;
            state.fullname = data.fullname;
            state.permission = data.permission;
            cache.set('authority-state', JSON.stringify(data));
        },

        /**
         * 权限刷新
         */
        updatePermission(state, data) {
            state.permission = data;
        },

        //退出登录
        logout(state, data) {
            state.token = '';
            state.authorize = false;
            state.avatar = '';
            state.uid = 0;
            state.role_id = 0;
            state.msg = 0;
            state.client_token = '';
            state.last_msg = [];
            state.last = 0;
            state.phone = '';
            state.last_login = '';
            state.fullname = '';
            state.permission = [];
            cache.clear();
        },
    }
}


//components/js/Cache


/**
 * 缓存工具类
 * @type {string}
 */

const prefix = 'hycrm_:_';//缓存前缀


/**
 * 获取缓存键值
 * @param key
 * @private
 */
function _getkey(key) {
    return prefix + _version + ':' + key;
}

/**
 * 获取缓存
 * @param key
 * @param defaultValue
 */
function get(key, defaultValue = null) {
    let data = localStorage.getItem(_getkey(key));
    if (!data) return defaultValue;
    try {
        let json = JSON.parse(data);
        if (json instanceof Object && typeof json.data != "undefined") {
            return json.data;
        }
        return defaultValue;
    } catch (e) {
        return defaultValue;
    }
}


/**
 * 设置缓存
 * @param key
 * @param value
 */
function set(key, value) {
    key = _getkey(key);
    let data = {
        data: value
    }
    localStorage.setItem(key, JSON.stringify(data));
}


/**
 * 删除缓存
 * @param key
 */
function del(key) {
    localStorage.removeItem(_getkey(key));
}

/**
 * 清空缓存
 */
function clear() {
    for (let key in localStorage) {
        if (key.substr(0, prefix.length) === prefix) {
            localStorage.removeItem(key);
        }
    }
}

export default {
    get, set, del, clear
}

	</textarea>
</div>